/* MQTT (over TCP) Example

   This example code is in the Public Domain (or CC0 licensed, at your option.)

   Unless required by applicable law or agreed to in writing, this
   software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
   CONDITIONS OF ANY KIND, either express or implied.
*/

#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include "esp_wifi.h"
#include "esp_system.h"
#include "nvs_flash.h"
#include "esp_event.h"
#include "esp_netif.h"
#include "protocol_examples_common.h"

#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/semphr.h"
#include "freertos/queue.h"

#include "lwip/sockets.h"
#include "lwip/dns.h"
#include "lwip/netdb.h"

#include "esp_log.h"
#include "mqtt_client.h"
#include "aht10.h"
#include "led.h"
#include "key.h"
#include "wifi.h"
#include "esp_sleep.h"
#include "esp_smartconfig.h"
#include "config.h"

MyIot myIot;

static const char *TAG = "IotSensor";


static void log_error_if_nonzero(const char *message, int error_code)
{
    if (error_code != 0) {
        ESP_LOGE(TAG, "Last error %s: 0x%x", message, error_code);
    }
}

/*
 * @brief Event handler registered to receive MQTT events
 *
 *  This function is called by the MQTT client event loop.
 *
 * @param handler_args user data registered to the event.
 * @param base Event base for the handler(always MQTT Base in this example).
 * @param event_id The id for the received event.
 * @param event_data The data for the event, esp_mqtt_event_handle_t.
 */
static void mqtt_event_handler(void *handler_args, esp_event_base_t base, int32_t event_id, void *event_data)
{
    ESP_LOGD(TAG, "Event dispatched from event loop base=%s, event_id=%d", base, event_id);
    esp_mqtt_event_handle_t event = event_data;
    // int msg_id;
    switch ((esp_mqtt_event_id_t)event_id) {
    case MQTT_EVENT_CONNECTED:
        ESP_LOGI(TAG, "MQTT_EVENT_CONNECTED");
        myIot.isMqttConn = 1;
        myIot.client = event->client;

        break;
    case MQTT_EVENT_DISCONNECTED:
        ESP_LOGI(TAG, "MQTT_EVENT_DISCONNECTED");
        myIot.isMqttConn = 0;
        break;

    case MQTT_EVENT_SUBSCRIBED:
        ESP_LOGI(TAG, "MQTT_EVENT_SUBSCRIBED, msg_id=%d", event->msg_id);
        break;
    case MQTT_EVENT_UNSUBSCRIBED:
        ESP_LOGI(TAG, "MQTT_EVENT_UNSUBSCRIBED, msg_id=%d", event->msg_id);
        break;
    case MQTT_EVENT_PUBLISHED:
        ESP_LOGI(TAG, "MQTT_EVENT_PUBLISHED, msg_id=%d", event->msg_id);
        break;
    case MQTT_EVENT_DATA:
        ESP_LOGI(TAG, "MQTT_EVENT_DATA");
        printf("TOPIC=%.*s\r\n", event->topic_len, event->topic);
        printf("DATA=%.*s\r\n", event->data_len, event->data);
        break;
    case MQTT_EVENT_ERROR:
        ESP_LOGI(TAG, "MQTT_EVENT_ERROR");
        if (event->error_handle->error_type == MQTT_ERROR_TYPE_TCP_TRANSPORT) {
            log_error_if_nonzero("reported from esp-tls", event->error_handle->esp_tls_last_esp_err);
            log_error_if_nonzero("reported from tls stack", event->error_handle->esp_tls_stack_err);
            log_error_if_nonzero("captured as transport's socket errno",  event->error_handle->esp_transport_sock_errno);
            ESP_LOGI(TAG, "Last errno string (%s)", strerror(event->error_handle->esp_transport_sock_errno));

        }
        break;
    default:
        ESP_LOGI(TAG, "Other event id:%d", event->event_id);
        break;
    }
}

void mqtt_app_start(void)
{
    esp_mqtt_client_config_t mqtt_cfg = {
        .broker.address.uri = "mqtt://mq.tongxinmao.com:18830",
    };
#if CONFIG_BROKER_URL_FROM_STDIN
    char line[128];

    if (strcmp(mqtt_cfg.broker.address.uri, "FROM_STDIN") == 0) {
        int count = 0;
        printf("Please enter url of mqtt broker\n");
        while (count < 128) {
            int c = fgetc(stdin);
            if (c == '\n') {
                line[count] = '\0';
                break;
            } else if (c > 0 && c < 127) {
                line[count] = c;
                ++count;
            }
            vTaskDelay(10 / portTICK_PERIOD_MS);
        }
        mqtt_cfg.broker.address.uri = line;
        printf("Broker url: %s\n", line);
    } else {
        ESP_LOGE(TAG, "Configuration mismatch: wrong broker url");
        abort();
    }
#endif /* CONFIG_BROKER_URL_FROM_STDIN */

    esp_mqtt_client_handle_t client = esp_mqtt_client_init(&mqtt_cfg);
    /* The last argument may be used to pass data to the event handler, in this example mqtt_event_handler */
    esp_mqtt_client_register_event(client, ESP_EVENT_ANY_ID, mqtt_event_handler, NULL);
    esp_mqtt_client_start(client);
}

void app_read_config()
{
    nvs_handle_t my_handle;
    nvs_open("storage", NVS_READONLY, &my_handle);
    nvs_get_u8(my_handle, "isSleepMode", &myIot.isSleepMode);
    nvs_close(my_handle);

    ESP_LOGI(TAG, "get config: %d", myIot.isSleepMode);
}
void app_write_config()
{
    nvs_handle_t my_handle;
    nvs_open("storage", NVS_READWRITE, &my_handle);
    nvs_set_u8(my_handle, "isSleepMode", myIot.isSleepMode);
    nvs_commit(my_handle);
    nvs_close(my_handle);

    ESP_LOGI(TAG, "set config: %d", myIot.isSleepMode);
}

static void app_goto_sleep()
{
    uint64_t sleepTime = 0;
    if (SLEEP_MQTT_PUBLIC_TIME * 1000 > esp_log_timestamp())
    {
        // Calculate sleep time based on elapsed time.
        sleepTime = SLEEP_MQTT_PUBLIC_TIME * 1000000 - esp_log_timestamp() * 1000;
    }
    else
    {
        sleepTime = SLEEP_MQTT_PUBLIC_TIME * 1000000;
    }
    ESP_LOGI(TAG, "elapsed: %d, sleep: %d", esp_log_timestamp(), sleepTime / 1000);
    esp_sleep_enable_timer_wakeup(sleepTime);
    esp_deep_sleep_start();
}

static void smartconfig_handler()
{
    isSmartConfig = true;
    led_start_blink(LED_Y, 400, 255);
    esp_wifi_disconnect();
    ESP_LOGI(TAG, "smartconfig start");
    ESP_ERROR_CHECK(esp_smartconfig_set_type(SC_TYPE_ESPTOUCH));
    smartconfig_start_config_t cfg = SMARTCONFIG_START_CONFIG_DEFAULT();
    ESP_ERROR_CHECK(esp_smartconfig_start(&cfg));
    while (1)
    {
        EventBits_t uxBits = xEventGroupWaitBits(s_wifi_event_group, CONNECTED_BIT | ESPTOUCH_DONE_BIT, true, false, portMAX_DELAY);
        if (uxBits & CONNECTED_BIT)
        {
            ESP_LOGI(TAG, "WiFi Connected to ap");
            led_stop_blink(LED_Y);
        }
        if (uxBits & ESPTOUCH_DONE_BIT)
        {
            ESP_LOGI(TAG, "smartconfig over");
            esp_smartconfig_stop();
            // vTaskDelete(NULL);
            isSmartConfig = false;
            break;
        }
    }
}

static void key_handler()
{
    // 短按按键切换睡眠模式
    EventBits_t triggeredEvents = xEventGroupWaitBits(key_event_group, SHORT_PRESS_EVENT_BIT, true, false, 0);
    if ((triggeredEvents & SHORT_PRESS_EVENT_BIT) != 0)
    {
        myIot.isSleepMode = !myIot.isSleepMode;
        app_write_config();
        led_start_blink(LED_W, 100, myIot.isSleepMode ? 1 : 2);
    }

    // 长按触发smartconfig
    triggeredEvents = xEventGroupWaitBits(key_event_group, LONG_PRESS_EVENT_BIT, true, false, 0);
    if ((triggeredEvents & LONG_PRESS_EVENT_BIT) != 0)
    {
        smartconfig_handler();
    }
}


void app_main(void)// is a task
{
    uint8_t sts = 0;
    ESP_LOGI(TAG, "[APP] Startup..");
    ESP_LOGI(TAG, "[APP] Free memory: %d bytes", esp_get_free_heap_size());
    ESP_LOGI(TAG, "[APP] IDF version: %s", esp_get_idf_version());

    esp_log_level_set("*", ESP_LOG_INFO);
    esp_log_level_set("mqtt_client", ESP_LOG_VERBOSE);
    esp_log_level_set(TAG, ESP_LOG_VERBOSE);
    esp_log_level_set("TRANSPORT_BASE", ESP_LOG_VERBOSE);
    esp_log_level_set("esp-tls", ESP_LOG_VERBOSE);
    esp_log_level_set("TRANSPORT", ESP_LOG_VERBOSE);
    esp_log_level_set("outbox", ESP_LOG_VERBOSE);

    ESP_ERROR_CHECK(nvs_flash_init());
    app_read_config();
    led_init();
    key_init();
    aht10_init();
    wifi_init();

    while(1)
    {
        switch (myIot.iotStep)
        {
        case IS_Idle:
            key_handler();
            myIot.iotStep = IS_Print;
            break;
        case IS_Print:
            sts = aht10_read(&myIot.temperature, &myIot.humidity);
            if(sts)
            {
                ESP_LOGE(TAG, "sensor busy.");
            }
            else
            {
                ESP_LOGI(TAG, "temperature %.2f, humidity: %.2f", myIot.temperature, myIot.humidity);
                myIot.iotStep = IS_WaitWiFi;
            }
            break;
        case IS_WaitWiFi:
            if(!myIot.isWifiConn)
            {
                EventBits_t uxBits = xEventGroupWaitBits(s_wifi_event_group, CONNECTED_BIT, true, false, 0);
                if (uxBits & CONNECTED_BIT)
                {
                    myIot.isWifiConn = true;
                    ESP_LOGI(TAG, "MQTT Start");
                    mqtt_app_start();
                    myIot.iotStep = IS_WaitMqtt;
                }
                else if(myIot.isSleepMode && esp_log_timestamp() > 30000)//如果睡眠模式开启，且超过30s仍未发送成功，直接睡眠
                {
                    myIot.iotStep = IS_Sleep;
                }
            }
            break;
        case IS_WaitMqtt:
            if(myIot.isMqttConn)
            {
                char buffer[32];
                sprintf(buffer, "%.2f,%.2f", myIot.temperature, myIot.humidity);
                esp_mqtt_client_publish(myIot.client, "/talon/sensor", buffer, 0, 1, 0);
                led_start_blink(LED_Y, 100, 1);
                if(myIot.isSleepMode)
                {
                    myIot.iotStep = IS_Sleep;
                }
                else
                {
                    myIot.iotStep = IS_WaitNext;
                }
            }
            break;
        case IS_WaitNext:
            myIot.waitNextTimer++;
            if(myIot.waitNextTimer >= MQTT_PUBLIC_TIME * 100) // MQTT_PUBLIC_TIME*1000/10
            {
                myIot.waitNextTimer = 0;
                myIot.iotStep = IS_Idle;
            }
            break;
        case IS_Sleep:
            app_goto_sleep();
            break;
        default:
            break;
        }

        vTaskDelay(10 / portTICK_PERIOD_MS);
    }
}
